﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TravelGenerator.IBusinessLayer.Account;
using TravelGenerator.BusinessObjects.ModelObjects;

namespace TravelGenerator.BusinessLayer.Account
{
    public class AccountManagement : IAccountManagement
    {
        #region Singleton

        private static AccountManagement instance;
        private static object syncRoot = new object();

        /// <summary>
        /// Gets the instance.
        /// </summary>
        /// <value>The instance.</value>
        public static AccountManagement Instance
        {
            get
            {
                //No concurentiel access
                lock (syncRoot)
                {
                    if (AccountManagement.instance == null)
                        AccountManagement.instance = new AccountManagement();
                }

                return instance;
            }
        }

        #endregion

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="AccountManagement"/> class.
        /// </summary>
        private AccountManagement()
        {

        }

        #endregion

        #region IAccountManagement Members

        /// <summary>
        /// Authenticates the account.
        /// </summary>
        /// <param name="login">The login.</param>
        /// <param name="password">The password.</param>
        /// <returns></returns>
        public Contact AuthenticateAccount(string login, string password)
        {
            return (from p in ContextManager.Instance.Context.Passport
                                 join c in ContextManager.Instance.Context.Contact on p.ContactID equals c.ContactID
                                 where c.Email == login
                                 && p.Email == login
                                 && p.Password == password
                                 select c).FirstOrDefault<Contact>();
        }

        #endregion

        #region Tools

        private Contact GetContactByID(int contactID)
        {
            IEnumerable<Contact> contacts = ContextManager.Instance.Context.Contact;

            Contact contact = (from p in contacts
                                 where p.ContactID == contactID
                                 select p).FirstOrDefault<Contact>();

            return contact;
        }

        #endregion
    }
}
